from ctypes import cdll, c_char_p, Structure, byref
import ctypes

# 定义SN_STATU结构体
class SN_STATU(Structure):
    _fields_ = [("code", ctypes.c_int),
               ("message", c_char_p * 4096)]

# 加载DLL
lib = cdll.LoadLibrary('D://SNOCR.dll')

# 设置函数参数类型
lib.apiSNInitOCRServer.argtypes = [c_char_p, ctypes.POINTER(SN_STATU)]
lib.apiSNInitOCRServer.restype = ctypes.c_int

lib.apiSNCreateOCRHandle.argtypes = [c_char_p, c_char_p, ctypes.POINTER(SN_STATU)]
lib.apiSNCreateOCRHandle.restype = ctypes.c_void_p

lib.apiSNGetKeyExpiresTime.argtypes = [ctypes.c_void_p, ctypes.POINTER(SN_STATU)]
lib.apiSNGetKeyExpiresTime.restype = c_char_p

lib.apiSNGetOCRFromImage.argtypes = [ctypes.c_void_p, c_char_p, ctypes.POINTER(SN_STATU)]
lib.apiSNGetOCRFromImage.restype = c_char_p

lib.apiSNDestroyOCRHandle.argtypes = [ctypes.c_void_p]
lib.apiSNDestroyOCRHandle.restype = ctypes.c_int

# 初始化变量
statu = SN_STATU()
key = b"SNKJ86RYDBY1YxafpLG3ep1R6NHFYLjz2UFFcE8Lx9Tq"
onnx_path = b"D://SNOCR.onnx"
image_path = b"D://7.jpg"

# 1. 启动OCR服务
ret = lib.apiSNInitOCRServer(onnx_path, byref(statu))
if ret < 0:
    print(f"Error:{statu.message.decode('utf-8')}")
    exit()

# 2. 创建OCR句柄
handle = lib.apiSNCreateOCRHandle(key, onnx_path, byref(statu))
if not handle:
    print(f"Error:{statu.message.decode('utf-8')}")
    exit()

# 3. 获取卡密到期时间
expires_time = lib.apiSNGetKeyExpiresTime(handle, byref(statu))
if not expires_time:
    print(f"Error:{statu.message.decode('utf-8')}")
    exit()
print(f"Expires Time: {expires_time.decode('utf-8')}")

# 4. 识别OCR，返回Json字符串
ocr_result = lib.apiSNGetOCRFromImage(handle, image_path, byref(statu))
if not ocr_result:
    print(f"Error:{statu.message.decode('utf-8')}")
    exit()
try:
    print(f"OCR Result: {ocr_result.decode('utf-8')}")
except UnicodeDecodeError:
    print(f"OCR Result: {ocr_result.decode('GBK')}")

# 5. 释放内存
lib.apiSNDestroyOCRHandle(handle)

# 等待输入，防止程序直接退出
input("Press Enter to exit...")